import { useRecoilValue } from 'recoil';

import { Avatar, Box, Tooltip, Typography } from '@mui/material';

import ChatbotIcon from 'assets/chatbot.png';
import UserIcon from 'assets/user.png';

import { userState } from 'state/auth0State';
import { IMessage } from 'state/chat';
import { avatarState } from 'state/element';

import MessageTime from './time';

interface Props {
  message: IMessage;
  show?: boolean;
  children: JSX.Element;
}

export default function AuthorWithAvatar({ message, show, children }: Props) {
  const user = useRecoilValue(userState);
  const avatars = useRecoilValue(avatarState);
  const avatarEl = avatars.find((e) => e.name === message.author);

  let src =
    message.authorIsUser ||
    user?.name === message.author ||
    message.author.toLowerCase() === 'user'
      ? UserIcon
      : ChatbotIcon;
  if (avatarEl) {
    src = avatarEl.url || URL.createObjectURL(new Blob([avatarEl.content!]));
  }

  return (
    <Box flex={1} display="flex" flexDirection="row" className="author-box">
      <Box width={40} height={40} mr={2} className="avatar-box">
        {!!show && src && (
          <Avatar
            sx={{ width: 40, height: 40, borderRadius: '50%' }}
            src={src}
            variant="rounded"
          />
        )}
      </Box>
      <Box flex={1}>
        <Box
          display="flex"
          flexDirection="row"
          alignItems="center"
          flex={1}
          className="name-box"
          marginBottom="4px"
        >
          <Tooltip title={message.author}>
            <Typography
              noWrap
              sx={{
                fontSize: '14px',
                fontWeight: 500,
                marginRight: '10px',
                color: 'text.primary',
                maxWidth: 180
              }}
            >
              {message.author}
            </Typography>
          </Tooltip>
          <MessageTime timestamp={message.createdAt} />
        </Box>
        {children}
      </Box>
    </Box>
  );
}
